//
//  CacheMemory.m
//  Dispatch
//
//  Created by hyeyeon on 14. 2. 5..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "CacheMemory.h"

#define CACHE_FOLER_NAME    @"cacheimg"
#define FILE_INFO           @"FILE_INFO"

@implementation CacheMemory
@synthesize delegate, mPath, fileManager, calendar, infoPath;

-(id)init{
    self = [super init];
    
    if (self) {
        self.fileManager = [NSFileManager defaultManager];
        self.mPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        self.infoPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
                         stringByAppendingPathComponent:FILE_INFO];
        self.calendar = [NSCalendar currentCalendar];
        dateFormatter = [[NSDateFormatter alloc] init];
        
    }
    return self;
}

#pragma mark 이미지부르기
//이미지 있으면 가져오고 없으면 nil리턴
-(UIImage*)findImage:(NSString*)fileName{
    
    fileName = [fileName stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    path = [NSString stringWithFormat:@"%@/%@", path,fileName];
    
    if ([self.fileManager fileExistsAtPath:path]) {
        
        NSData *filedata = [fileManager contentsAtPath:path];
//        NSLog(@"ㅇㅣ미지 있음 : %@",path);
        
        UIImage *image = [UIImage imageWithData:filedata];
        return image;
    }
    return nil;
}

#pragma mark 이미지 저장하기
-(void)saveImage:(NSData*)imageData andFileName:(NSString*)fileName{
    
    fileName = [fileName stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    
    //쓰레드로 빼자
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        path = [NSString stringWithFormat:@"%@/%@", path,fileName];
        
//        NSLog(@"저장이미지 : %@",fileName);
        
//        NSDate *date = [NSDate date];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//        NSString *dateStr = [dateFormatter stringFromDate:date];
//        
//        NSMutableArray *array;
        
//        if ([self.fileManager fileExistsAtPath:self.infoPath]) {
//            array = [NSMutableArray arrayWithContentsOfFile:self.infoPath];
//        }else{
//            array = [[NSMutableArray alloc] init];
//        }
//        [array addObject:[NSDictionary dictionaryWithObjectsAndKeys:dateStr,@"date",path,@"path", nil]];
        
        
        if ([imageData writeToFile:path atomically:NO]) {
            //            NSLog(@"이미지저장");
        }else{
            //            NSLog(@"이미지 저장실패");
        }
        
//        if ([array writeToFile:self.infoPath atomically:NO]) {
//            //        NSLog(@"이미지 정보 저장함");
//            
//            if ([imageData writeToFile:path atomically:NO]) {
//                //            NSLog(@"이미지저장");
//            }else{
//                //            NSLog(@"이미지 저장실패");
//            }
//            
//        } else{
////            NSLog(@"이미지 정보 저장 실패");
//        }
    });
    
    
}


#pragma mark - 이미지 지우기
//모두
-(void)emptyCache{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSArray *array = [[NSFileManager defaultManager] subpathsAtPath:[paths objectAtIndex:0]];
    
    for (NSString *string in array) {
        NSString *str;
        str = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@",string];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:str]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:str error:nil];
        }
    }
    
//    NSMutableArray *infoArray = [NSMutableArray arrayWithContentsOfFile:self.infoPath];
//    [infoArray removeAllObjects];
//    if ([infoArray writeToFile:self.infoPath atomically:NO]) {
//        
//    }else{
//        
//    }
}


//몇일전인거 지우기
-(void)removeCacheBefore:(int)day{
    
    if ([self.fileManager fileExistsAtPath:self.infoPath]) {
        NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:self.infoPath];
        
        int i = 0;
        while (i < [array count]) {
            
            NSString *dateStr = [[array objectAtIndex:i] objectForKey:@"date"];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSDate *date = [dateFormatter dateFromString:dateStr];
            
            if ([self formattedDateCompareToNow:date] < day*-1) {
                NSString *path = [[array objectAtIndex:i] objectForKey:@"path"];
                if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                    
                    NSLog(@"삭제 : %d : %@",i,path);
                    [self.fileManager removeItemAtPath:path error:nil];
                }
                [array removeObjectAtIndex:i];
            }else{
                i++;
            }
        }
        
        if ([array writeToFile:self.infoPath atomically:NO]) {

        }else{

        }
    }
    
}

-(NSInteger)formattedDateCompareToNow:(NSDate*)date{
    
    return (int)[date timeIntervalSinceNow] / (60*60*24);
    
}







-(NSString*)fixFileName:(NSString*)fileName{
    NSArray *array = [fileName componentsSeparatedByString:@"/"];
    fileName = [NSString stringWithFormat:@"%@_%@",[array objectAtIndex:[array count]-2],[array lastObject]];
    fileName = [fileName stringByReplacingOccurrencesOfString:@".jpg" withString:@""];
    return fileName;
}

@end
